package com.fafu.common.web.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.fafu.common.web.bean.Result;
import com.fafu.common.web.bean.ResultUtil;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 父控制器
 *
 * @param <T>
 * @author hc
 */
public class BaseController<T> {
    private IService<T> service;

    public BaseController(IService<T> service) {
        this.service = service;
    }

    /**
     * 根据id查询
     *
     * @param id
     * @return
     */
    @GetMapping("/getById/{id}")
    public Result getById(@PathVariable("id") Serializable id) {
        T obj = service.getById(id);
        return ResultUtil.success(obj);
    }

    /**
     * 添加
     *
     * @param obj
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody T obj) {
        service.save(obj);
        return ResultUtil.success();
    }

    /**
     * 更新
     *
     * @param obj
     * @return
     */
    @PutMapping("/updateById")
    public Result updateById(@RequestBody T obj) {
        service.updateById(obj);
        return ResultUtil.success();
    }

    /**
     * 根据id删除单个
     *
     * @param id
     * @return
     */
    @DeleteMapping("/deleteById/{id}")
    public Result deleteById(@PathVariable Serializable id) {
        UpdateWrapper<T> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status", 2)
                .eq("id", id);
        service.update(updateWrapper);
        return ResultUtil.success();
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/batchDelete")
    public Result batchDelete(@RequestParam String ids) {
        List<String> idList = Arrays.stream(ids.split(",")).collect(Collectors.toList());
        UpdateWrapper<T> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("status", 2).in("id", idList);
        service.update(updateWrapper);
        return ResultUtil.success();
    }
}
